package xp2p.svc;

import java.io.IOException;

import xp2p.adv.jxta.AdvBase;
import net.jxta.discovery.DiscoveryEvent;
import net.jxta.discovery.DiscoveryListener;
import net.jxta.discovery.DiscoveryService;

public abstract class RequestorBase<T extends AdvBase> extends BeatBase implements DiscoveryListener
{	
	private ListenerBase<T> listener;
		
	public RequestorBase(String docType, String advClassName, ListenerBase<T> listener)
	{
		this.setListener(listener);		
		this.getListener().setDocType(docType);		
		this.getListener().setAdvClassType(advClassName);
	}
	
	public RequestorBase(ListenerBase<T> listener)
	{
		this.setListener(listener);
	}	
	
	public RequestorBase()
	{
	}
	
	@Override
	protected void beat()
	{
		DiscoveryService dsvc = getGroup().getDiscoveryService();		
		try
		{
			getListener().process(dsvc.getLocalAdvertisements(DiscoveryService.ADV, AdvBase.TypeTag, getListener().getDocType()));		
			dsvc.getRemoteAdvertisements(null, DiscoveryService.ADV, AdvBase.TypeTag, getListener().getDocType(), 1024, getListener());
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	public ListenerBase<T> getListener()
	{
		return listener;
	}

	public void setListener(ListenerBase<T> listener)
	{
		this.listener = listener;
	}
	
	@Override
	public void discoveryEvent(DiscoveryEvent event)
	{
		listener.discoveryEvent(event);		
	}
}
